const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const KEY_DIR = path.join(__dirname, '../keys');

if (!fs.existsSync(KEY_DIR)) {
  fs.mkdirSync(KEY_DIR);
}

const KEY_PAIR_PATH = {
  private: path.join(KEY_DIR, 'private.pem'),
  public: path.join(KEY_DIR, 'public.pem')
};

function generateKeyPair() {//生成RSA密钥对
  const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  });

  fs.writeFileSync(KEY_PAIR_PATH.private, privateKey);
  fs.writeFileSync(KEY_PAIR_PATH.public, publicKey);

  console.log('RSA Key Pair generated and saved.');
}

if (!fs.existsSync(KEY_PAIR_PATH.private) || !fs.existsSync(KEY_PAIR_PATH.public)) {
  generateKeyPair();
}

module.exports = {
  getPublicKey: () => fs.readFileSync(KEY_PAIR_PATH.public).toString(),
  decryptWithPrivateKey: (encryptedData) => {
    const privateKey = fs.readFileSync(KEY_PAIR_PATH.private);
    const buffer = Buffer.from(encryptedData, 'base64');
    const decrypted = crypto.privateDecrypt(
      {
        key: privateKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
        oaepHash: "sha256"
      },
      buffer
    );
    return decrypted.toString('utf8');
  },
};